package com.hq.base.web;

import com.hq.base.domain.BaseObject;
import com.hq.base.service.BaseService;
import com.hq.common.domain.Result;
import com.hq.common.domain.ResultCode;
import com.hq.common.domain.SearchObject;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * Created by hezj on 2015/7/4 0004.
 */
public abstract class BaseController extends BaseObject{

    private static final ModelAndView ERROR_VIEW=new ModelAndView("error");

    public Result getResult(){
        return new Result();
    }

    public Result getResult(String message){
        return new Result(ResultCode.OK,message);
    }
    public Result getResultWithUrl(String url){
        return new Result(url);
    }

    public Result getResult(String url,String message){
        return new Result(url,message);
    }

    public Result getResult(ResultCode code, Map data, String message){
        return new Result(code,data,message);
    }

    public Result getResult(ResultCode code,  String message){
        return new Result(code,message);
    }

    public ModelAndView getErrorView(String message){
        ERROR_VIEW.addObject("message",message);
        return ERROR_VIEW;
    }

    @RequestMapping("/list")
    @ResponseBody
    public Result get(SearchObject condition){
        condition.setPageNum(condition.getPageNum()-1);
        return getResult().addAllData(getService().queryWithCount(condition))
                .addData("pageNum", condition.getPageNum()+1)
                .addData("pageSize", condition.getPageSize());
    }

    @RequestMapping("/{id}")
    @ResponseBody
    public Result get(@PathVariable(value = "id")long id){
        return getResult().addData("instance", getService().get(id));
    }

    public abstract BaseService getService();
}
